package com.ck.texting;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.ck.texting.bean.SalaryMsg;
import com.ck.texting.util.ExcelUtil;
import com.ck.texting.util.SmsSend;

import java.io.IOException;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class MainActivity extends AppCompatActivity {
    TextView tv;
    AppCompatButton btn;
    android.support.v7.app.ActionBar actionBar;
    String path;
    List<SalaryMsg> list;
    public static final int RequestCode = 1;
    public static final int RequestCode2 = 2;
    public static final String TAG = "msg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = findViewById(R.id.tv);
        btn = findViewById(R.id.btn);
         actionBar= getSupportActionBar();
        getPermission();


        if (path == null) {
            path= getExcel();
            if (path != null) {
                list = readExcel(path);
                if (list != null) {
                    actionBar.setTitle("已读取"+list.size()+"条数据");
                }
            }
            //new MTask().execute(path);
        }


        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(list==null||list.size()==0){
                    Toast("表格数据为空!");
                    return;
                }
                executeAsyncTask();
            }
        });

    }

    /**
     * 得到文件路径
     *
     * @return
     */
    public String getExcel() {
        Intent intent = getIntent();
        Uri data = intent.getData();
        if (data == null) {
            return null;
        }
        if(data.toString().startsWith("content")){
            return getRealPathFromUri(this, data);
        };
        return data.getPath();
       /* if (null == data) {
            return null;
        }
        String str = Uri.decode(data.getEncodedPath());
        return str;*/
    }

    public List<SalaryMsg> readExcel(String path) {
        try {
            List<SalaryMsg> map = ExcelUtil.readExcel(this,path, "sheet1");

            if (null == map) {
                Toast(ExcelUtil.errmsg);
            }
            return map;

        } catch (IOException e) {

            e.printStackTrace();
        }
        return null;

    }

    public void getPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.SEND_SMS},
                        RequestCode);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        RequestCode2);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        RequestCode2);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS},
                        RequestCode2);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == RequestCode) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //showToast("权限已申请");
            }
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public void Toast(String msg) {
        Toast.makeText(MainActivity.this,msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 在这个栗子中将展示使用rxjava执行一个最简单的异步任务
     * 栗子将会完成如下工作
     * 1. 在任务执行前显示进度条
     * 2. 线程休眠1秒，模拟异步任务的执行，然后返回一段字符串作为执行结果
     * 3. 关闭进度条，处理异步任务的执行结果
     */
    private void executeAsyncTask() {
        //Observable#create方法创建一个异步任务
       Observable.create(new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(Subscriber<? super Integer> subscriber) {
                //在call方法中执行异步任务


                for (int i = 0; i < list.size(); i++) {
                    SalaryMsg msg = list.get(i);
                    // 发送方法!
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        SmsSend.sendSMS(MainActivity.this,msg.phoneNumber,msg.msgContent);
                    }
                    subscriber.onNext(1+i);

                    SystemClock.sleep(1000);

                }
                //调用subscriber#onNext方法将执行结果返回
                //调用subscriber#onCompleted方法完成异步任务
                subscriber.onCompleted();
            }
        })
                .subscribeOn(Schedulers.io())//指定异步任务在IO线程运行
                .observeOn(AndroidSchedulers.mainThread())//制定执行结果在主线程运行
                .subscribe(new Subscriber<Integer>() {

                    ProgressDialog progressDialog;

                    @Override
                    public void onStart() {
                        //在异步任务执行前打开进度条
                        if (progressDialog == null) {
                            progressDialog = new ProgressDialog(MainActivity.this);
                            // 设置进度条风格，风格为长形
                            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                            // 设置ProgressDialog 标题
                            progressDialog.setTitle("注意!");
                            // 设置ProgressDialog 提示信息
                            progressDialog.setMessage("请等待,正在发送...");
                            // 设置ProgressDialog 标题图标
                            // 设置ProgressDialog 进度条进度
                            progressDialog.setMax(list.size());
                            // 设置ProgressDialog 的进度条是否不明确
                            progressDialog.setIndeterminate(false);

                            progressDialog.show();
                        }

                        super.onStart();

                    }

                    @Override
                    public void onCompleted() {
                        //在异步任务执行完成后关闭进度条
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        actionBar.setTitle("发送完毕!");
                        list.clear();
                    }

                    @Override
                    public void onError(Throwable e) {
                        //如果异步任务执行失败则关闭进度条，并打印错误日志
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
                        Toast("执行任务失败!");
                        Log.e(TAG, "onError: execute async task fail", e);
                    }

                    @Override
                    public void onNext(Integer s) {
                        //处理异步任务的执行结果
                        Log.i(TAG, "onNext"+s.toString());
                        progressDialog.setProgress(s);


                    }
                });

    }

    public static String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

}
